//
//  ToolAppInfo.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON

extension Tools {
    
    /// 获取当前版本号
    static public var version_Str: String {
        guard let cVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { return "" }
        return cVersion
    }
    
    /// 获取当前设备系统
    static public var sysVersion: String { return UIDevice.current.systemVersion }
    
    // 应用第一次启动
    static public func isFirstLaunch() -> Bool {
         let hasBeenLaunched = "hasBeenLaunched"
         let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunched)
         if isFirstLaunch {
             UserDefaults.standard.set(true, forKey: hasBeenLaunched)
             UserDefaults.standard.synchronize()
         }
         return isFirstLaunch
    }
     
    // 当前版本第一次启动
    static public func isFirstLaunchOfNewVersion() -> Bool {
         // 主程序版本号
         guard let infoDictionary = Bundle.main.infoDictionary,
              let majorVersion = infoDictionary["CFBundleShortVersionString"] as? String else { return false }
         // 上次启动的版本号
         let hasBeenLaunchedOfNewVersion = "hasBeenLaunchedOfNewVersion"
         let lastLaunchVersion = UserDefaults.standard.string(forKey: hasBeenLaunchedOfNewVersion)
          
         // 版本号比较
         let isFirstLaunchOfNewVersion = majorVersion != lastLaunchVersion
         if isFirstLaunchOfNewVersion {
             UserDefaults.standard.set(majorVersion, forKey: hasBeenLaunchedOfNewVersion)
             UserDefaults.standard.synchronize()
         }
         return isFirstLaunchOfNewVersion
    }
}

/// 版本比较
extension Tools {
    
    /// 获取appstore上的最新版本号
    static public func getAppStoreVersion(_ appId: String, _ block: BlockSingleStr? = nil) {
        // 请求超时时长
        let reqTimeOut: TimeInterval = 15
        let url = "https://itunes.apple.com/cn/lookup?id=" + appId
        AF.request(url, method: .get, parameters: [:], requestModifier: {
            $0.timeoutInterval = reqTimeOut
        }).response { resp in
            if let value = resp.value, let buf = value, let v = String(bytes: buf, encoding: String.Encoding.utf8) {
                let dic = Tools.getDictionaryFromJSONString(v)
                if let results = dic["results"] as? [[String: Any?]],
                   let version = results.first?["version"] as? String {
                    Log_y.print_("appstore_version = \(version)")
                    block?(version)
                } else {
                    block?("")
                }
            } else {
                block?("")
            }
        }
    }
    
    /// 跳转AppStore，进行版本更新
    static public func updateVersion(_ appId: String) {
        guard let url = URL(string: "https://itunes.apple.com/cn/app/%E8%8E%B1%E4%BB%98mpos/id" + appId + "?mt=8") else { return }
        if #available(iOS 11.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
           UIApplication.shared.canOpenURL(url)
        }
    }
    
     // 版本比较
     static public func versionCompare(v1: String, v2: String) -> String {
         //判断合法性
         if checkSeparat(vString: v1) == "" || checkSeparat(vString: v2) == ""{
         return "只支持 '.''-'/''*'_'作为分隔符"
         }
         //获得两个数组
         let v1Arr = cutUpNumber(vString: v1) as! [String]
         let v2Arr = cutUpNumber(vString: v2) as! [String]
         // 比较版本号
         return compareNumber(v1Arr: v1Arr, v2Arr: v2Arr)
     }
     
     // 提取连接符
     static private func checkSeparat(vString:String) -> String {
         var separated:String = ""
         if vString.contains("."){  separated = "." }
         if vString.contains("-"){  separated = "-" }
         if vString.contains("/"){  separated = "/" }
         if vString.contains("*"){  separated = "*" }
         if vString.contains("_"){  separated = "_" }
         
         return separated
     }
     
     // 提取版本号
     static private func cutUpNumber(vString:String) -> NSArray {
         let  separat = checkSeparat(vString: vString)
         let b = NSCharacterSet(charactersIn:separat) as CharacterSet
         let vStringArr = vString.components(separatedBy: b)
         return vStringArr as NSArray
     }
     
     // 比较版本
     static private func compareNumber(v1Arr:[String],v2Arr:[String]) -> String {
         for i in 0..<v1Arr.count{
             if  Int(v1Arr[i])! != Int(v2Arr[i])! {
                 if Int(v1Arr[i])! > Int(v2Arr[i])! {
                     return "v1 > v2"
                 }else{
                     return "v1 < v2"
                 }
             }
         }
         return "v1 == v2"
     }
}
